package com.wuuxiang.dynamic.mongo.aop;

import org.aopalliance.aop.Advice;
import org.springframework.aop.Pointcut;
import org.springframework.aop.support.AbstractPointcutAdvisor;
import org.springframework.aop.support.ComposablePointcut;
import org.springframework.aop.support.annotation.AnnotationMatchingPointcut;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

public class DynamicMongoAnnotationAdvisor extends AbstractPointcutAdvisor implements BeanFactoryAware {

    private static final long serialVersionUID = -2817226965764925606L;

    private final Advice advice;
    private final Pointcut pointcut;


    public DynamicMongoAnnotationAdvisor(DynamicMongoAnnotationInterceptor advice) {
        this.advice = advice;
        this.pointcut = buildPointcut();
    }

    @Override
    public Pointcut getPointcut() {
        return this.pointcut;
    }

    @Override
    public Advice getAdvice() {
        return this.advice;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        if (this.advice instanceof BeanFactoryAware) {
            ((BeanFactoryAware) this.advice).setBeanFactory(beanFactory);
        }
    }

    private Pointcut buildPointcut() {
        //类上面添加了注解
        Pointcut cpc = new AnnotationMatchingPointcut(MongoDS.class, true);
        //方法上添加了注解
        Pointcut mpc = AnnotationMatchingPointcut.forMethodAnnotation(MongoDS.class);
        //方法优于类
        return new ComposablePointcut(cpc).union(mpc);
    }
}
